//
//  NoteResultViewController.m
//  TripGo
//
//  Created by dllo on 15/7/18.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "NoteResultViewController.h"
#import "AFNetworkHandler.h"
#import "TravelTableViewCell.h"
#import "TravelViewController.h"
#import "UIViewController+Example.h"
#import "MJRefresh.h"
#import "TravelPushViewController.h"

static int page = 1;
@interface NoteResultViewController () <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) UIActivityIndicatorView *activityIndicator;
@end

@implementation NoteResultViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}
//自己创建视图控制器的时候的初始化
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if ([super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        //通知的注册一般放在初始化中
        [self createNoCenter];
    }
    return self;
}
#pragma mark - NotificationCenter 通知中心
- (void)createNoCenter
{
    //通知中心单例 (在任何地方使用的通知中心都是同一个)
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    //注册通知
    [center addObserver:self selector:@selector(chuanzhi:) name:@"passStr" object:nil];
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"title.jpg"] forBarMetrics:UIBarMetricsDefault];
    
    for (UIView *aview in self.navigationController.navigationBar.subviews) {
        if ([aview.class isEqual:[UISearchBar class]]) {
            aview.hidden = _isHiden;
        }
    }
}
- (void)chuanzhi:(NSNotification *)notification
{
    self.flag = NO;
    if ([self.name isEqualToString:notification.object] == YES) {
        self.flag = YES;
    }
    if (self.flag == YES) {
        self.arr = [NSMutableArray array];
        [self.tableView reloadData];
    }
    self.name = notification.object;
    // 定义菊花控件
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [self.view addSubview:self.activityIndicator];
    self.activityIndicator.color = [UIColor grayColor];
    self.activityIndicator.center = CGPointMake(self.view.center.x, self.view.center.y - 64);
    [_activityIndicator release];
    [self.activityIndicator startAnimating];
    [self getData:1 where:@"upPush"];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = [NSString stringWithFormat:@"%@游记", self.name];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ButtonBack_normal"] style:UIBarButtonItemStylePlain target:self action:@selector(PopViewController)];
    
    [self createTableView];
    [self getData:page where:nil];
    [self exampleUpPush];
    [self exampleDownPush];
    // Do any additional setup after loading the view.
}
- (void)getData:(int)page where:(NSString *)where;
{
    NSString *strPush = [NSString stringWithFormat:@"http://chanyouji.com/api/search/trips.json?q=%@&page=%d", self.name, page];
    [AFNetworkHandler GetWithAFNByURL:strPush completion:^(id result) {
        NSArray *tempArr = result;
//        if (tempArr.count == 0) {
//            UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有符合条件的结果" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
//            [al show];
//            [al release];
//            return;
//        }
        NSMutableArray *temp = [NSMutableArray array];
        temp = [Travel arrayWithModelByArray:tempArr];
        if ([where isEqualToString:@"upPush"] == YES || [where isEqualToString:nil] == YES) {
            for (Travel *t in temp) {
                [self.arr addObject:t];
            }
            [self.tableView reloadData];
            // 拿到当前的上拉刷新控件，结束刷新状态
            [self.tableView.footer endRefreshing];
        } else if ([where isEqualToString:@"downPush"] == YES) {
            self.arr = [NSMutableArray array];
            for (NSInteger i = temp.count - 1; i >= 0 ; i--) {
                Travel *t = temp[i];
                [self.arr insertObject:t atIndex:0];
            }
            [self.tableView reloadData];
            // 拿到当前的下拉刷新控件，结束刷新状态
            [self.tableView.header endRefreshing];
        }
        [self.activityIndicator stopAnimating];
    }];
}

- (void)exampleDownPush
{
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}
- (void)exampleUpPush
{
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
    }];
    
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}
#pragma mark 下拉刷新数据
- (void)loadNewData
{
    NSString *where = @"downPush";
    static int a = 1;
    [self getData:a where:where];
    page = 1;
}
- (void)loadMoreData
{
    // 1.向上拖动时page自加
    NSString *where = @"upPush";
    page++;
    [self getData:page where:where];
}
- (void)PopViewController
{
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[TravelViewController class]]) {
            [self.navigationController popToViewController:controller animated:YES];
        }
    }
}
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //self.tableView.contentInset = UIEdgeInsetsMake(10, 0, 70, 0);
    [self.view addSubview:self.tableView];
    [_tableView release];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelTableViewCell *cell = [TravelTableViewCell tableView:tableView indexPath:indexPath];
    cell.travel = self.arr[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TravelPushViewController *travelPvc = [[TravelPushViewController alloc] init];
    travelPvc.url = [NSString stringWithFormat:@"http://chanyouji.com/api/trips/%@.json", [self.arr[indexPath.row] TravelId]];
    _isHiden = NO;
    for (UIView *aview in self.navigationController.navigationBar.subviews) {
        if ([aview.class isEqual:[UISearchBar class]]) {
            aview.hidden = YES;
        }
    }
    
    [self.navigationController pushViewController:travelPvc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 225;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSArray *visibleCells = [self.tableView visibleCells];
    for (TravelTableViewCell *cell in visibleCells) {
        [cell cellOnTableView:self.tableView didScrollOnView:self.view];
    }
}
#pragma mark - 开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.tabBarController.tabBar.hidden = YES;
}
#pragma mark - 结束减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    self.tabBarController.tabBar.hidden = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
